package com.teemor.open.openauth;

import com.teemor.common.bean.utils.BeanConvertor;
import com.teemor.common.bean.utils.UUIDUtils;
import com.teemor.common.bean.utils.enums.ResultCode;
import com.teemor.common.bean.utils.excption.TeemorException;
import com.teemor.common.bean.utils.redis.RedisUtils;
import com.teemor.open.openauth.model.AuthResource;
import com.teemor.open.openauth.model.AuthUserModel;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @Description:
 * @author zhoulk
 * @date: 2020/5/29
 */
public class AuthUtils {

    private static final String AUTH_RESOURCE = "AUTH_RESOURCE";

    public static AuthUserModel getUser(String token) {
        Object user = Optional.ofNullable(RedisUtils.getObject(token)).orElseThrow(() -> new TeemorException(ResultCode.NOTLOGIN));
        return BeanConvertor.convertBean(user, AuthUserModel.class);
    }

    public static void cacheToken(AuthUserModel authUserModel) {
        RedisUtils.setObjectAndTime(authUserModel.getToken(), authUserModel, authUserModel.getTokenExpire());
        RedisUtils.setObjectAndTime(authUserModel.getRefreshToken(), authUserModel, authUserModel.getTokenExpire());
    }

    public static AuthUserModel refreshToken(String refreshToken) {
        Object object = RedisUtils.getObject(refreshToken);
        if (Objects.isNull(object) || !(object instanceof AuthUserModel)) {
            return null;
        }
        String token = UUIDUtils.generateUuid();
        refreshToken = UUIDUtils.generateUuid();
        AuthUserModel authUserModel = (AuthUserModel) object;
        authUserModel.setToken(token);
        authUserModel.setRefreshToken(refreshToken);
        cacheToken(authUserModel);
        return authUserModel;
    }

    public static void cacheResource(List<AuthResource> authResources) {
        RedisUtils.setObject(AUTH_RESOURCE, authResources);
    }

    public static void cleanResource() {
        RedisUtils.del(AUTH_RESOURCE);
    }

    public static List<AuthResource> getCheckResource() {
        Object list = RedisUtils.getObject(AUTH_RESOURCE);
        if (list instanceof List)
        return (List<AuthResource>) list;
        return new ArrayList<>();
    }
}
